package com.yc.server.user.impl;

import java.io.IOException;
import java.io.StringWriter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import btsm.bean.sqlUsersWork;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yc.dao.SystemDAO;
import com.yc.dao.model.JSONUser;
import com.yc.server.user.ILoginService;

public class LoginService implements ILoginService {
	private static final Log log = LogFactory.getLog(LoginService.class);
	private SystemDAO systemDAO;
	public LoginService(){
		systemDAO = new SystemDAO();
	}
	
	public String login(String userName, String password) {
		log.info("login by webservice for["+userName+":"+password+"]");
		JSONUser jsonUser = new JSONUser();
		ObjectMapper mapper = new ObjectMapper(); 
		 StringWriter sw = new StringWriter();  ;  
		if(userName == null || "".equalsIgnoreCase(userName)
			|| password == null || "".equalsIgnoreCase(password)	){
			jsonUser.setStatus(false);
			try {
				mapper.writeValue(sw, jsonUser);
			} catch (Exception e) {
				log.error("covert object ot json failed : ", e);
			}    
			return  sw.getBuffer().toString();//返回失败
		}
		sqlUsersWork PC = new sqlUsersWork("users", "0");
		boolean result = PC.checkLogin(userName, password);
		jsonUser.setStatus(result);
		if(result){
			jsonUser.setUser(systemDAO.getUserByName(userName));
		}
		
		try {
			mapper.writeValue(sw, jsonUser);
		} catch (Exception e) {
			log.error("covert object ot json failed : ", e);
		}  
		 log.info("The check value is ["+ sw.getBuffer().toString()+"]");
		return sw.getBuffer().toString();
	}

}
